//
//  BVShoppingCartViewController.m
//  BuyVegetable
//
//  Created by yushanchang on 16/9/28.
//  Copyright © 2016年 com.yinding. All rights reserved.
//

#import "BVShoppingCartViewController.h"
#import "BVLoginViewController.h"
#import "BVLoginoutShoppingCarts.h"
#import "BVEmptyShoppingCarts.h"
#import "BVShoppingCartTool.h"
#import "BVShoppingCart.h"
#import "BVShoppingCartFrame.h"
#import "BVShoppingCartCell.h"
#import "BVConfirmOrderViewController.h"

#define CGRECT CGRectMake(0,0,ScreenW,ScreenH-64-49)
#define SHOPPINGCART_CELL_IDENTIFIER @"BVShoppingCartCell"

@interface BVShoppingCartViewController ()
<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
// 全选
@property (weak, nonatomic) IBOutlet UIButton *selectAllButton;
// 总价
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UIButton *shoppingButton;

@property (nonatomic, strong) BVLoginoutShoppingCarts *logoutView;
@property (nonatomic, strong) BVEmptyShoppingCarts *emptyView;
@property (nonatomic, strong) BVShoppingCartTool *shoppingCartTool;
@property (nonatomic, strong) NSMutableArray *dataArr;
// 计算frame
@property (nonatomic, strong) NSMutableArray *frameArr;
@property (nonatomic, assign) NSInteger num;

@property (strong, nonatomic) IBOutlet UIView *subView;

@end

@implementation BVShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 选择子视图
//    [self chooseChildView];
//    [self fetchShoppingCartData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    [self chooseChildView];
    [self fetchShoppingCartData];
}

- (void)fetchShoppingCartData {

    [self.hud show:YES];
    [self.shoppingCartTool fetchShoppingCartData:^(NSArray *dataArr) {
        [self.hud hide:YES];
        self.dataArr = (NSMutableArray *)dataArr;
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.hud hide:YES];
        [self showError:@"加载失败"];
    }];
}

- (void)setTableView:(UITableView *)tableView {
    _tableView = tableView;
    [tableView registerClass:[BVShoppingCartCell class] forCellReuseIdentifier:SHOPPINGCART_CELL_IDENTIFIER];
}

- (void)setSelectAllButton:(UIButton *)selectAllButton {
    _selectAllButton = selectAllButton;
    [selectAllButton setImage:IMAGE_NAMED(@"huiduihao") forState:UIControlStateNormal];
    [selectAllButton setImage:IMAGE_NAMED(@"hongduihao") forState:UIControlStateSelected];
}

- (void)chooseChildView {
    
        self.viewType = 0;
        if (!self.user.isLogin) { // 未登录
            self.logoutView = [[BVLoginoutShoppingCarts alloc] initWithFrame:CGRECT];
    
            __weak __typeof(self) weakSelf = self;
            self.logoutView.logoutBlock = ^{
                BVLoginViewController *login = [[BVLoginViewController alloc] init];
                [weakSelf.navigationController pushViewController:login animated:YES];
            };
            [self.subView setHidden:YES];
            [self.view addSubview:self.logoutView];

        } else { // 登录
            self.logoutView = nil;
            [self.logoutView removeFromSuperview];
            
            if (self.viewType == 0) {
                self.emptyView = [[BVEmptyShoppingCarts alloc] initWithFrame:CGRECT];
                __weak __typeof(self) weakSelf = self;
                self.emptyView.emptyClick = ^{ //购物
                    weakSelf.tabBarController.selectedIndex = 1;
                };
                [self.view addSubview:self.emptyView];
            } else {
                [self.emptyView removeFromSuperview];
            }
        }
}

#pragma mark -
#pragma mark - UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BVShoppingCartCell *shoppingcart_cell = [tableView dequeueReusableCellWithIdentifier:SHOPPINGCART_CELL_IDENTIFIER];
    BVShoppingCart *shoppingcart = self.dataArr[indexPath.row];
    shoppingcart_cell.shoppingCart = shoppingcart;
    shoppingcart_cell.shoppingCartFrame = self.frameArr[indexPath.row];
    
    shoppingcart_cell.radioButton.selected = shoppingcart.is_selected;
    shoppingcart_cell.indexPath = indexPath;
    
#pragma mark - 
#pragma mark - 操作相关
    shoppingcart_cell.radioBlock = ^(NSIndexPath *indexPath,BOOL is_selected){
        BVShoppingCart *shoppingcart = self.dataArr[indexPath.row];
        shoppingcart.is_selected = is_selected;
        
        /*剔除失效的单选按钮*/
        NSInteger valid_count = 0; NSInteger disvalid_count = self.dataArr.count;
        for (BVShoppingCart *shoppingcart in self.dataArr) {
            
            if ([shoppingcart.status isEqualToString:@"1"]) {
                disvalid_count--;
                if (shoppingcart.is_selected) {
                    valid_count++;
                }
            }
        }
        
        if (valid_count == self.dataArr.count - disvalid_count) {
            self.selectAllButton.selected = YES;
        } else {
            self.selectAllButton.selected = NO;
        }
        
        [self updateTotalPrice];
//        [self.tableView reloadData];
    };
    
    
    shoppingcart_cell.addBlock = ^(NSIndexPath *indexPath) {
        [self.hud show:YES];
        BVShoppingCart *shoppingcart = self.dataArr[indexPath.row];
        __weak BVShoppingCartViewController *weakSelf = self;
        [self.shoppingCartTool addGoodsToShoppingCart:shoppingcart.ID success:^(NSString *code){
            [weakSelf.hud hide:YES];
            if ([code isEqualToString:@"0"]) {
                [weakSelf updateTotalPrice];
//                NSLog(@"goods_num22:%ld",shoppingcart.goods_num);
            } else if ([code isEqualToString:@"10021"]) {
                [weakSelf showMessage:@"此商品库存不足"];
            } else if ([code isEqualToString:@"10019"]) {
                [weakSelf showMessage:@"此商品已下架"];
            }
        } failure:^(NSError *error) {
            [weakSelf.hud hide:YES];
            [weakSelf showMessage:@"增加商品失败"];
        }];
    };
    
    shoppingcart_cell.minusBlock = ^(NSIndexPath *indexPath) {
        [self.hud show:YES];
        BVShoppingCart *shoppingcart = self.dataArr[indexPath.row];
        __weak BVShoppingCartViewController *weakSelf = self;
        [self.shoppingCartTool minusGoodsToShoppingCart:shoppingcart.ID success:^(NSString *code) {
            [weakSelf.hud hide:YES];
            if ([code isEqualToString:@"0"]) {
                [self updateTotalPrice];
//                NSLog(@"goods_num22:%ld",shoppingcart.goods_num);
            } else if ([code isEqualToString:@"10021"]) {
                [weakSelf showMessage:@"此商品库存不足"];
            } else if ([code isEqualToString:@"10019"]) {
                [weakSelf showMessage:@"此商品已下架"];
            }

        } failure:^(NSError *error) {
            [weakSelf.hud hide:YES];
            [weakSelf showMessage:@"减少商品失败"];
        }];
    };
    return shoppingcart_cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [self.frameArr[indexPath.row] cellHeight];
}

#pragma mark -
#pragma mark - 购买
- (IBAction)shoppingClick:(id)sender {
    NSMutableArray *selectedArr = [[NSMutableArray alloc] init];
    for (BVShoppingCart *shoppingcart in self.dataArr) {
        if (shoppingcart.is_selected && [shoppingcart.status isEqualToString:@"1"]) {
            [selectedArr addObject:shoppingcart];
        }
    }
//    NSLog(@"==>%ld",shoppingcartArr.count);
    if (selectedArr.count == 0) {
        [self showMessage:@"购物车为空"];
        return;
    } else {
        BVConfirmOrderViewController *confirm = [[BVConfirmOrderViewController alloc] init];
        confirm.dataSource = selectedArr;
        [self.navigationController pushViewController:confirm animated:YES];
    }
}

#pragma mark -
#pragma mark - 全选
- (IBAction)selectAllClick:(UIButton *)button {
    button.selected = !button.selected;
    for (BVShoppingCart *shopping_cart in self.dataArr) {
        shopping_cart.is_selected = button.selected;
    }
    [self updateTotalPrice];
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark - 计算价格
- (void)updateTotalPrice {
    float total_price = 0;
    int i = 0;
    for (BVShoppingCart *shoppingcart in self.dataArr) {
        if (shoppingcart.is_selected && ![shoppingcart.status isEqualToString:@"0"]) {
            total_price += shoppingcart.goods_num * [shoppingcart.all_price floatValue];
            i++;
        }
    }
    self.totalLabel.text = [NSString stringWithFormat:@"共%.2f元",total_price];
}

- (void)setDataArr:(NSMutableArray *)dataArr {
    _dataArr = dataArr;
    for (BVShoppingCart *shoppingCart in dataArr) {
        BVShoppingCartFrame * shoppingCartFrame = [[BVShoppingCartFrame alloc] init];
        shoppingCartFrame.shoppingCart = shoppingCart;
        [self.frameArr addObject:shoppingCartFrame];
    }
}

- (NSMutableArray *)frameArr {
    if (!_frameArr) {
        _frameArr = [[NSMutableArray alloc] init];
    }
    return _frameArr;
}

- (BVShoppingCartTool *)shoppingCartTool {
    if (!_shoppingCartTool) {
        _shoppingCartTool = [[BVShoppingCartTool alloc] init];
    }
    return _shoppingCartTool;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
